import { View } from '@tarojs/components';
import { Component } from 'react';
import { getOrderDetail, reqRefound, confirmOrder } from '@/service/apis/order/index';
import Taro from '@tarojs/taro';
import dayjs from 'dayjs';
import { getOrderStatus } from '../utils';
import WaitPay from './components/WaitPay';
import WaitTake from './components/WaitTake';
import Complete from './components/Complete';
import Refound from './components/Refound';
import Canceled from './components/Canceled';
import './index.scss';

enum OrderStatus {
  /** 待支付 */
  WaitPay = 1,
  /** 带自提 */
  WaitTake = 2,
  /** 已完成 */
  Complete = 3,
  /** 已取消 */
  Canceled = 4,
  /** 申请退款 */
  Request = 5,
  /** 已退款 */
  Refound = 6,
}

/**
 * 订单详情页
 * @returns
 */
export default class OrderDetail extends Component {
  state: any = {
    productInfo: null,
    orderDetail: null,
    shopInfo: null,
  };
  componentDidMount() {
    const query = Taro.getCurrentInstance().router?.params;
    if (query?.type && query.orderCode) {
      this.getOrderDetail(query?.type, query.orderCode);
    }
  }

  getTimeStr = (time: string) => {
    let newStr = '';
    if (time.indexOf('12:00:00')) {
      newStr = time.replace('12:00:00', '08:00 - 12:00');
    } else if (time.indexOf('18:00:00')) {
      newStr = time.replace('18:00:00', '14::00 - 18:00');
    }
    return newStr;
  };

  getOrderDetail = async (type: string, orderCode: string) => {
    try {
      const { data } = await getOrderDetail({
        type: type,
        order_sn: orderCode,
      });
      console.log('data', data);
      const { detail } = data;
      console.log('getOrderStatus(detail): ', getOrderStatus(detail.order_status));
      this.setState({
        orderDetail: {
          orderStatus: getOrderStatus(detail.order_status),
          order_status: detail.order_status,
          time: this.getRemainPayTime(detail),
          serviceType: detail.order_type === 4 ? 2 : detail.freight_type,
          // serviceType: detail.freight_type,
          address: detail.order_address,
          userName: detail.user_name,
          date: this.getTimeStr(detail.order_pickup_time),
          userPhone: detail.user_mobile,
          payType: detail.order_pay,
          totalPrice: detail.order_price,
          orderType: detail.order_type === 4 ? 1 : detail.order_type,
          expressPrice: 0,
          productPrice: detail.product_vip_price || detail.order_price,
          orderNumber: detail.order_sn,
          createDate: dayjs(detail.order_add_time).valueOf(),
          payDate: detail.pay_time,
          qrcodeContent: detail.order_fetch_code,
          getDate: this.getTimeStr(detail.order_pickup_time),
          refoundDesc: '无',
          refoundType: '仅退款',
          refoundNumber: 'M202203101526356245120255',
          refoundTime: detail.update_time,
          lat: Number(detail.lat),
          lng: Number(detail.lng),
        },
        shopInfo: {
          name: detail.store_name,
          address: detail.store_address,
          logo: detail.store_logo,
          // brand: '卡西欧',
          phone: detail.store_mobile,
        },
        productInfo: {
          pic_url: detail.goods_pic_url,
          name: detail.goods_name,
          desc: detail.product_specifications,
          duration: '',
          payWay: detail.order_pay === 1 ? '线上支付' : '线下支付',
          price: detail.product_vip_price,
          count: detail.order_number,
          skuInfo: detail.specifications
          // id: ,
        },
      });
    } catch (err) {
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  getRemainPayTime = (orderDetail: any) => {
    const { order_add_time } = orderDetail;
    const orderStatus = getOrderStatus(orderDetail.order_status);
    if (orderStatus === 1) {
      const createTime = dayjs(order_add_time).valueOf();
      const remainTime = 20 * 60 * 1000 + createTime - dayjs().valueOf();
      if (remainTime > 0) {
        return Math.floor(remainTime / 1000);
      }
      return 0;
    }
  };

  onRefound = () => {
    const { orderDetail } = this.state;
    Taro.showModal({
      title: '申请退款',
      content: '确认申请退款吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await reqRefound({ order_sn: orderDetail.orderNumber });
            Taro.showToast({
              title: '申请成功',
            });
            setTimeout(() => {
              Taro.navigateBack({});
            }, 1000);
          } catch (err) {
            Taro.showToast({
              title: err?.message,
              icon: 'none',
            });
          }
        }
      },
    });
  };

  onConfirm = () => {
    const { orderDetail } = this.state;
    Taro.showModal({
      title: '确认收货',
      content: '如您已收到购买的产品，完成确认收货操作后，订单将更新为已完成状态。',
      cancelText: "取消",
      confirmText: "确定",
      success: async (res) => {
        if (res.confirm) {
          try {
            await confirmOrder({ order_sn: orderDetail.orderNumber });
            Taro.showToast({
              title: '确认成功',
            });
            setTimeout(() => {
              Taro.navigateBack({});
            }, 1000);
          } catch (err) {
            Taro.showToast({
              title: err?.message,
              icon: 'none',
            });
          }
        }
      },
    });
  }

  render() {
    const { productInfo, orderDetail, shopInfo } = this.state;
    return (
      orderDetail && (
        <View className="product-order-detail">
          {orderDetail.orderStatus === OrderStatus.WaitPay ? (
            <WaitPay orderDetail={orderDetail} productInfo={productInfo} shopInfo={shopInfo} />
          ) : orderDetail.orderStatus === OrderStatus.WaitTake ? (
            <WaitTake
              onRefound={this.onRefound}
              orderDetail={orderDetail}
              productInfo={productInfo}
              shopInfo={shopInfo}
              onConfirm={this.onConfirm}
            />
          ) : orderDetail.orderStatus === OrderStatus.Complete ? (
            <Complete
              onRefound={this.onRefound}
              orderDetail={orderDetail}
              productInfo={productInfo}
              shopInfo={shopInfo}
            />
          ) : orderDetail.orderStatus === OrderStatus.Canceled ? (
            <Canceled orderDetail={orderDetail} productInfo={productInfo} shopInfo={shopInfo} />
          ) : (
            <Refound orderDetail={orderDetail} productInfo={productInfo} shopInfo={shopInfo} />
          )}
        </View>
      )
    );
  }
}
